package com.yt.order.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.order.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.order.mapper.WorkOrderEvaluationMapper;
import com.yt.order.models.service.IWorkOrderEvaluationService;
import com.yt.order.models.bo.WorkOrderEvaluationSaveBO;
import com.yt.order.models.dto.WorkOrderEvaluationDTO;
import com.yt.order.models.service.IWorkOrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.dubbo.config.annotation.DubboReference;
import com.yt.sys.models.dto.EmpRatingStatsDTO;
import com.yt.sys.models.service.IEmpRatingStatsService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import java.math.BigDecimal;
import com.yt.sys.models.bo.EmpRatingStatsSaveBO;
import java.util.Date;

/**
 * 订单评价控制器
 *
 * @author yzz
 * @Date 2025-09-15 14:06:29
 */
@DubboService
public class WorkOrderEvaluationServiceImpl extends ServiceImpl<WorkOrderEvaluationMapper, WorkOrderEvaluationDTO> implements IWorkOrderEvaluationService{

    @Resource
    private YmlConfig ymlConfig;
    
    @Autowired
    private IWorkOrderInfoService workOrderInfoService;
    
    @DubboReference
    private IEmpRatingStatsService empRatingStatsService;

    @Override
    public boolean add(WorkOrderEvaluationSaveBO saveBO) {
        // 校验外键关联数据是否存在
        if (saveBO.getWorkOrderId() != null) {
            // 校验工单是否存在
            if (workOrderInfoService.selectById(saveBO.getWorkOrderId()) == null) {
                // 工单不存在，不能添加评价
                throw new RuntimeException("工单不存在，无法添加评价");
            }
        }
        
        WorkOrderEvaluationDTO dto = new WorkOrderEvaluationDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        boolean result = this.insert(dto);
        
        // 如果评价添加成功，且包含员工ID和星级，则更新员工星级统计
        if (result && saveBO.getUserId() != null && saveBO.getStarRating() != null) {
            updateEmployeeRatingStats(saveBO.getUserId(), saveBO.getStarRating());
        }
        
        return result;
    }
    
    /**
     * 更新员工星级统计
     * @param userId 员工ID
     * @param starRating 星级评分
     */
    private void updateEmployeeRatingStats(Long userId, Integer starRating) {
        // 查询是否已存在该员工的星级统计记录
        EntityWrapper<EmpRatingStatsDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
        EmpRatingStatsDTO stats = empRatingStatsService.selectOne(wrapper);
        
        if (stats == null) {
            // 如果不存在，则创建新的星级统计记录
            EmpRatingStatsSaveBO saveBO = new EmpRatingStatsSaveBO();
            saveBO.setUserId(userId);
            saveBO.setEvaluationCount(1);
            saveBO.setTotalRating(new BigDecimal(starRating));
            
            // 根据星级设置对应的星级计数
            if (starRating == 5) {
                saveBO.setFiveStarCount(1);
                saveBO.setFourStarCount(0);
            } else if (starRating == 4) {
                saveBO.setFiveStarCount(0);
                saveBO.setFourStarCount(1);
            } else {
                saveBO.setFiveStarCount(0);
                saveBO.setFourStarCount(0);
            }
            
            empRatingStatsService.add(saveBO);
        } else {
            // 如果已存在，则更新星级统计记录
            int newEvaluationCount = stats.getEvaluationCount() + 1;
            BigDecimal newTotalRating = stats.getTotalRating()
                    .multiply(new BigDecimal(stats.getEvaluationCount()))
                    .add(new BigDecimal(starRating))
                    .divide(new BigDecimal(newEvaluationCount), 1, BigDecimal.ROUND_HALF_UP);
            
            stats.setEvaluationCount(newEvaluationCount);
            stats.setTotalRating(newTotalRating);
            
            // 根据星级更新对应的星级计数
            if (starRating == 5) {
                stats.setFiveStarCount(stats.getFiveStarCount() + 1);
            } else if (starRating == 4) {
                stats.setFourStarCount(stats.getFourStarCount() + 1);
            }
            
            // 更新修改时间
            stats.setUpdateTime(new Date());
            empRatingStatsService.updateById(stats);
        }
    }
}